<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

class f_file_Directory
{
    private static $instances;

	private $directory;
	private $basename;
	private $dirname;
	private $filename;

	private function __construct($directory)
	{
		$this->directory = realpath($directory);

		if(is_dir($this->directory))
		{
			$this->getDirProperties($this->directory);

			return $this;
		}
		throw new Exception("Directory doesn't exist");
	}

	/**
	 * Instanciate directory
	 * ex : getInstance("/home/web/www");
	 * 
	 * @param string $file
	 * @return f_file_Directory
	 */
	public static function getInstance($directory)
	{
        if(!isset(self::$instances[$directory]))
        {
            self::$instances[$directory] = new self($directory);
        }
		return self::$instances[$directory];
	}

	/**
	 * Get dir properties for constructor
	 *
	 * @param string $directory
	 */
	private function getDirProperties($directory)
	{
		$infos = array();

		$infos = pathinfo($directory);

		foreach ($infos as $key => $info)
		{
			$this->$key = $info;
		}
	}

	/**
	 * Get formatted creation date
	 *
	 * @return string
	 */
	public function getCreationDate()
	{
		return $this->formatDate(filectime($this->directory));
	}

	/**
	 * Get formatted creation date
	 *
	 * @return string
	 */
	public function getModificationDate()
	{
		return $this->formatDate(filemtime($this->directory));
	}

	/**
	 * Format date in current lang
	 *
	 * @param integer $timeStamp
	 * @return string
	 */
	private function formatDate($timeStamp)
	{
		$date = f_date_Date::getInstance(date("Y-m-d H:i:s", $timeStamp));

		$date = f_date_DateFormat::formatByLang($date, f_core_Context::getLang());

		return $date;
	}

	/**
	 * Return all files and directory in current directory
	 *
	 * @return array<object>
	 */
	public function getContent()
	{
		$result = array();

		$directoryContent = scandir($this->getPath());

		foreach ($directoryContent as $content)
		{
			$filePath = $this->getPath().DS.$content;

			if(is_dir($filePath))
			{
				$result[] = f_file_Directory::getInstance($filePath);
			}
			elseif (is_file($filePath))
			{
				$result[] = f_file_File::getInstance($filePath);
			}
		}

		return $result;
	}

	/**
	 * Return all subdirs
	 *
	 * @return array<object>
	 */
	public function getSubdirs()
	{
		$result = array();

		$directoryContent = scandir($this->getPath());

		foreach ($directoryContent as $content)
		{
			if($content != "." && $content != "..")
			{
				$filePath = $this->getPath().DS.$content;

				if(is_dir($filePath))
				{
					$result[] = f_file_Directory::getInstance($filePath);
				}
			}
		}

		return $result;
	}

	/**
	 * Return all files
	 *
	 * @return array<object>
	 */	
	public function getFiles()
	{
		$result = array();

		$directoryContent = scandir($this->getPath());

		foreach ($directoryContent as $content)
		{
			$filePath = $this->getPath().DS.$content;

			if(is_file($filePath))
			{
				$result[] = f_file_File::getInstance($filePath);
			}
		}

		return $result;
	}

    /**
     * Get current folder size
     **/
    public function getSize($dir = null)
    {
        if(is_null($dir))
        {
            $dir = $this->getPath();
        }

        $s = stat($dir);
        $space = $s["blocks"]*512;

        if(is_dir($dir))
        {
            $dh = opendir($dir);

            while (($file = readdir($dh)) !== false)
            {
                if ($file != "." and $file != "..")
                {
                    $space += $this->getSize($dir.DS.$file);
                }
            }
            closedir($dh);
        }
        return $space;
    }

    /**
     * Get current folder size formatted
     * @return string
     */
    public function getFormattedSize($lang = null)
    {
        $bytes = $this->getSize();

        switch($lang)
        {
            case 'fr' : $symbols = array('o', 'Ko', 'Mo', 'Go', 'To', 'Po', 'Eo', 'Zo', 'Yo'); break;
            default : $symbols = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); break;
        }
        $exp = $bytes ? floor(log($bytes) / log(1024)) : 0;

        return sprintf('%.2f '.$symbols[$exp], ($bytes/pow(1024, floor($exp))));
    }

	///////////////////////////////////////////////////

	/**
	 * Return the complete path
	 * ex : /home/web/www
	 *
	 * @return string
	 */
	public function getPath()
	{
		return $this->directory;
	}

	/**
	 * Return the directory name
	 * ex : www
	 *
	 * @return string
	 */
	public function getDirName()
	{
		return $this->basename;
	}

	/**
	 * Return the parent directory path
	 * ex : /home/web
	 *
	 * @return string
	 */
	public function getParentDir()
	{
		return $this->dirname;
	}
}